<template>
  <!-- 线边库（新增表）表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="45%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.plantId"
              placeholder="请输入工厂"
              clearable
              @change="changePlant"
              style="width: 400px"
              filterable
            >
              <el-option
                v-for="item in plantList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ plantCode(formData.plantId) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车间" prop="workshopId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workshopId"
              placeholder="请选择车间"
              clearable
              @change="changeWorkCenter"
              :disabled="formData.plantId === ''"
              style="width: 400px"
              filterable
            >
              <el-option
                v-for="item in workCenters"
                :key="item.id"
                :label="`${item.shopFloorCode}-${item.shopFloorName}`"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.workshopCode }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="线边库编号" prop="produceStorageCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.produceStorageCode"
              placeholder="请输入线边库编号"
              clearable
            />

            <span v-else>{{ formData.produceStorageCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外部编号" prop="externalCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.externalCode"
              placeholder="请输入外部编号"
              clearable
            />

            <span v-else>{{ formData.externalCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="线边库类型" prop="produceStorageType">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.produceStorageType"
              placeholder="请选择线边库类型"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'ProduceStorageType'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "ProduceStorageType",
                formData.produceStorageType
              )
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12"
          ><el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              :maxlength="255"
              show-word-limit
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESPRODUCESTORAGEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getPlantList();
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  workshopId: [{ required: true, message: "请选择车间", trigger: "change" }],
  produceStorageCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入线边库编号",
      trigger: "blur",
    },
  ],
  externalCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入外部编号",
      trigger: "blur",
    },
  ],
  produceStorageType: [
    { required: true, message: "请选择线边库类型", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  plantCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  workshopCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  workshopName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const changePlant = (id: any) => {
  formData.plantId = id;
  formData.plantCode = plantCode(id);
  //工厂变更清除关联内容
  formData.workshopId = "";
  formData.workshopCode = "";
  workCenters.value = [];
  getWorkCenter();
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
//工作中心
const workCenters = ref([]);
async function getWorkCenter() {
  if (formData.plantId) {
    await request({
      url: "mdm/mdmshopfloor/getList",
      method: "post",
      data: { plantId: formData.plantId, enabled: 1 },
    }).then((res) => {
      workCenters.value = res.data;
    });
  }
}
const changeWorkCenter = (id: any) => {
  formData.workshopId = id;
  workCenters.value.forEach((item) => {
    if (item.id === id) {
      formData.workshopCode = item.shopFloorCode;
      formData.workshopName = item.shopFloorName;
    }
  });
};
let formData = reactive({
  id: "",
  organizationId: "",
  plantId: "",
  workshopId: "",
  produceStorageCode: "",
  externalCode: "",
  produceStorageType: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  plantCode: "",
  workshopCode: "",
  workshopName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        organizationId,
        plantId,
        workshopId,
        produceStorageCode,
        externalCode,
        produceStorageType,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        plantCode,
        workshopCode,
        workshopName,
      } = newVal;
      Object.assign(formData, {
        id,
        organizationId,
        plantId,
        workshopId,
        produceStorageCode,
        externalCode,
        produceStorageType,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        plantCode,
        workshopCode,
        workshopName,
      });
      getWorkCenter();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.plantId = "";
  formData.workshopId = "";
  formData.produceStorageCode = "";
  formData.externalCode = "";
  formData.produceStorageType = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.plantCode = "";
  formData.workshopCode = "";
  formData.workshopName = "";
}

const loading = ref(false);

/** 线边库（新增表）保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesproducestorage/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
